package com.gy.util;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName ReflectionUtil
 * @Author YangFu
 * @Date 2024/3/19 20:51
 * @Version 1.0
 */
public class ReflectionUtil {

    /**
     * 反射
     * 将实体类转换为查询字符串
     * @param entity 实体类对象
     * @return 查询字符串
     */
    public static String convertEntityToQueryString(Object entity) {
        Map<String, Object> params = new LinkedHashMap<>();
        Class<?> clazz = entity.getClass();

        try {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true); // 设置字段可访问
                Object value = field.get(entity);
                if (value != null) {
                    String key = field.getName();
                    String encodedValue = URLEncoder.encode(value.toString(), StandardCharsets.UTF_8.toString());
                    params.put(key, encodedValue);
                }
            }
        } catch (IllegalAccessException e) {
//            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        // 构建查询字符串
        StringBuilder queryStringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (queryStringBuilder.length() > 0) {
                queryStringBuilder.append("&");
            }
            queryStringBuilder.append(entry.getKey()).append("=").append(entry.getValue());
        }
        return queryStringBuilder.toString();
    }
}
